//
//  MarsWebViewController.m
//  WKWebDemo
//
//  Created by yangpenghua on 2018/3/27.
//  Copyright © 2018年 linzi. All rights reserved.
//

// MainScreen Height&Width
#define Mars_Screen_Height      [[UIScreen mainScreen] bounds].size.height
#define Mars_Screen_Width       [[UIScreen mainScreen] bounds].size.width

//状态栏高度
#define Mars_Status_Bar_Height       [[UIApplication sharedApplication] statusBarFrame].size.height
// 导航栏高度
#define Mars_Navigation_Bar_Height   (Mars_Status_Bar_Height + 44.0)
// 底部TabBar高度
#define Mars_TabBar_Height           (Mars_Status_Bar_Height > 21.0 ? 83.0 : 49.0)
//  Iphone X 底部TabBar增加的高度
#define Mars_TabBar_Addition_Height  (Mars_Status_Bar_Height > 21.0 ? 34.0 : 0.0)

//魔蝎 公积金 测试环境
#define MoxieSDKKEY      @"40429df8551a4799b7e9b19c7e6f1f44"

#import "ThorWebViewController.h"
#import "ThorProgressLayer.h"
#import <WebKit/WebKit.h>
#import "MarsCategory.h"
#import "MarsManager.h"
#import "MoxieSDK.h"
#import "ThorBaseConfig.h"
#import "ThorServiceManager.h"

@interface ThorWebViewController ()<WKNavigationDelegate,WKUIDelegate, EmergencyContactManagerDelegate, ThorWebViewDelegate,MoxieSDKDelegate,ThorServiceManagerDelegate>

@property (nonatomic, strong) UIBarButtonItem   *backItem;
@property (nonatomic, strong) UIBarButtonItem   *closeItem;
@property (nonatomic, strong) UIView            *lineView;
@property (nonatomic, strong) WKWebView         *webView;

/** 进度条 */
@property (nonatomic, strong) ThorProgressLayer      *progressLayer;
/** 访问通讯录管理类 */
@property (nonatomic, strong) MarsAddressBookManager *addressBookManager;
/** 获取紧急联系人类 */
@property (nonatomic, strong) MarsEmergencyContactManager *emergencyContactManager;

/** 获取地理位置管理类 */
@property (nonatomic, strong) MarsLocationManager    *locationManager;
/** 网络请求 */
@property (nonatomic, strong) ThorServiceManager     *serviceManager;

/** 是否重新刷新 */
@property (nonatomic, assign) BOOL  refreshStatus;
/** 通讯录联系人 */
@property (nonatomic, copy) NSString *phoneParamsString;

@end

@implementation ThorWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.lineView];
    if (@available(iOS 11.0, *)) {
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.webView];
    if (self.navigationController) {
        [self.navigationController setNavigationBarHidden:NO];
    }
    // 请求url链接
    [self requestWebUrl];
    //  添加导航栏左侧按钮
    [self addLeftButton];
    //  监听title变动
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
}

- (void)requestWebUrl{
    NSString *userPhone = [ThorBaseConfig sharedConfig].userPhone;
    NSString *userId = [ThorBaseConfig sharedConfig].userId;
    NSString *channel = [ThorBaseConfig sharedConfig].channel;
    if (userPhone.length > 0 && userId.length > 0 && channel.length > 0) {
        [self.serviceManager thor_userCheckWithUserPhone:userPhone userId:userId channel:channel];
    }
}

#pragma mark - ThorServiceManagerDelegate
/** 验证登录成功 */
- (void)thor_userCheckSuccess:(NSString *)h5Url{
    if (h5Url.length > 0) {
        _webUrlStr = h5Url;
        
        if (self.webUrlStr.length > 0) {
            NSMutableURLRequest *webRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.webUrlStr] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15.0];
            [self.webView loadRequest:webRequest];
        }
    }
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self resetViewsFrame];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    //  隐藏底部TabBar
    if (self.navigationController) {
        [self.navigationController setHidesBottomBarWhenPushed:YES];
    }
    
    //  设置导航栏背景颜色
    if ([self respondsToSelector:@selector(thorSetNavBarBackgroundColor)]) {
        UIColor *bgColor = [self thorSetNavBarBackgroundColor];
        UIImage *bgImage = [self imageWithColor:bgColor];
        if (bgImage) {
            [self.navigationController.navigationBar setBackgroundImage:bgImage forBarMetrics:UIBarMetricsDefault];
            [self resetViewsFrame];
        }
    }
    
    //  设置导航栏背景图片
    if ([self respondsToSelector:@selector(thorSetNavBarBackgroundImage)]) {
        UIImage *bgImage = [self thorSetNavBarBackgroundImage];
        if (bgImage) {
            [self.navigationController.navigationBar setBackgroundImage:bgImage forBarMetrics:UIBarMetricsDefault];
            [self resetViewsFrame];
        }
    }
    
    if (self.refreshStatus) {
        //  重置刷新状态
        self.refreshStatus = NO;
        
        NSMutableURLRequest *webRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.webUrlStr] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15.0];
        [self.webView loadRequest:webRequest];
    }
}

//  由于如果导航栏透明的情况下会坐标原点从（0， 0）设置frame， 不透明的情况下坐标原点就是（0，64)开始设置frame.
- (void)resetViewsFrame{
    CGFloat lineViewY = 0.0;
    if (self.navigationController.navigationBar.isTranslucent) {
        lineViewY = Mars_Navigation_Bar_Height;
    }
    self.lineView.frame = CGRectMake(0.0, lineViewY, Mars_Screen_Width, 1.0);
    CGFloat webViewH = Mars_Screen_Height - CGRectGetMaxY(_lineView.frame) - Mars_TabBar_Addition_Height - Mars_Navigation_Bar_Height;
    if (self.navigationController.navigationBar.isTranslucent) {
        webViewH = Mars_Screen_Height - CGRectGetMaxY(_lineView.frame) - Mars_TabBar_Addition_Height;
    }
    self.webView.frame = CGRectMake(0.0, CGRectGetMaxY(_lineView.frame), Mars_Screen_Width, webViewH);
    self.progressLayer.frame = CGRectMake(0.0, lineViewY+1.0, Mars_Screen_Width, 2.0);
}

#pragma mark - 注册监听title和进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"title"]){
        if (object == self.webView) {
            self.navigationItem.title = self.webView.title;
            if ([self.webView.title isEqualToString:@"人脸识别"]) {
                //  判断授权状态
                [MarsAuthorizeManager mars_authorizeCamera];
                [MarsAuthorizeManager mars_authorizeMicrophone];
            }
        } else {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
}

#pragma mark - 添加关闭按钮
- (void)addLeftButton{
    self.navigationItem.leftBarButtonItem = self.backItem;
}

#pragma mark - 返回按钮
- (UIBarButtonItem *)backItem{
    if (!_backItem) {
        _backItem = [[UIBarButtonItem alloc] init];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        NSBundle *bundle = [NSBundle bundleForClass:[self class]];
        NSURL *bundleURL = [bundle URLForResource:@"ThorFramework" withExtension:@"bundle"];
        NSBundle *resourceBundle = [NSBundle bundleWithURL: bundleURL];
        UIImage *image = [UIImage imageNamed:@"thor_nav_back" inBundle:resourceBundle compatibleWithTraitCollection:nil];
//        UIImage *image = [UIImage imageNamed:@"thor_nav_back"];
        [btn setImage:image forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(backNative) forControlEvents:UIControlEventTouchUpInside];
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        btn. frame=CGRectMake(15, 5, 38, 38);
        _backItem.customView = btn;
    }
    return _backItem;
}

#pragma mark - 点击返回的方法
- (void)backNative{
    //判断是否有上一层H5页面
    if ([self.webView canGoBack]) {
        //如果有则返回
        [self.webView goBack];
        
        //同时设置返回按钮和关闭按钮为导航栏左边的按钮
        self.navigationItem.leftBarButtonItems = @[self.backItem, self.closeItem];
    } else {
        [self closeNative];
    }
}

- (UIBarButtonItem *)closeItem{
    if (!_closeItem) {
        _closeItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(closeNative)];
        [_closeItem setTintColor:[UIColor blackColor]];
    }
    return _closeItem;
}

- (void)closeNative
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(thorWebViewExit)]) {
        [self.delegate thorWebViewExit];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 页面加载过程
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    /** 添加进度条 */
    [self.view.layer addSublayer:self.progressLayer];
    [self.progressLayer startLoad];
}

// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    [self.progressLayer finishedLoad];
}

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    [self.progressLayer finishedLoad];
}

#pragma mark - 页面跳转的代理方法
// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSURL *requestUrl = navigationAction.request.URL;
    NSString *requestString = requestUrl.absoluteString;
    NSString *requestHost = requestUrl.host;//域名
    //  URL拦截
    if ([self tellPhoneInterupt:requestString]) {
        //  电话拦截
        decisionHandler(WKNavigationActionPolicyCancel);
    } else if ([requestString rangeOfString:@"about:blank"].location != NSNotFound){
        //  空页面 不跳转
        decisionHandler(WKNavigationActionPolicyCancel);
    } else if ([requestString rangeOfString:@"itunes.apple.com"].location != NSNotFound) {
        //  跳转到AppStore
        NSString *appStoreUrlStr = [requestString mars_urlEncode];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appStoreUrlStr]];
        decisionHandler(WKNavigationActionPolicyCancel);
    } else if ([self handleNativeObjcInteractiveWithUrl:requestUrl]) {
        //  处理原生与web的交互
        decisionHandler(WKNavigationActionPolicyCancel);
    } else if ([requestHost rangeOfString:@"bailingpay.com"].location != NSNotFound) {
        //  域名判断是否添加marsInfo
        if ([requestString rangeOfString:@"marsInfo="].location != NSNotFound){
            //  如果拼接masInfo再拼接sdkInfo
            if ([requestString rangeOfString:@"sdkInfo="].location == NSNotFound) {
                //  添加sdkInfo参数
                NSString *appendParamsUrl = [self addSDKInfoRequestUrlParamas:requestUrl];
                NSMutableURLRequest *webRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:appendParamsUrl] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15.0];
                [self.webView loadRequest:webRequest];
                
                decisionHandler(WKNavigationActionPolicyAllow);
            } else {
                decisionHandler(WKNavigationActionPolicyAllow);
            }
        } else {
            decisionHandler(WKNavigationActionPolicyAllow);
        }
     } else {
        decisionHandler(WKNavigationActionPolicyAllow);
     }
}

// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    decisionHandler(WKNavigationResponsePolicyAllow);
}

// 接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
}

//  截取打电话
- (BOOL)tellPhoneInterupt:(NSString *)urlStr{
    if ([urlStr hasPrefix:@"sms:"] || [urlStr hasPrefix:@"tel:"]) {
        UIApplication * app = [UIApplication sharedApplication];
        if ([app canOpenURL:[NSURL URLWithString:urlStr]]) {
            [app openURL:[NSURL URLWithString:urlStr]];
        }
        return YES;
    }
    return NO;
}

//  处理原生与H5交互
- (BOOL)handleNativeObjcInteractiveWithUrl:(NSURL *)loadUrl{
    BOOL interactiveResult = NO;
    //  URL query参数字典
    NSDictionary *paramsDict = [loadUrl mars_queryParams];
    NSString *nameString = [paramsDict[@"name"] description];
    NSString *paramsString = [paramsDict[@"params"] description];
    NSDictionary *paramsDictionary = [NSDictionary dictionary];
    if (paramsString) {
        NSData *paramsDecodeData = [NSString mars_safeUrlBase64Decode:paramsString];
        if (paramsDecodeData) {
            paramsDictionary = [NSJSONSerialization JSONObjectWithData:paramsDecodeData options:0 error:nil];
        }
    }
    if ([nameString isEqualToString:@"ADDRESS_BOOK"]) {
        //  获取通讯录
        [self accessAddressBookWithEmergencyContact:NO];
        interactiveResult = YES;
    } else if ([nameString isEqualToString:@"EMERGENCY_CONTACT"]) {
        //  打开选择系统联系人
        [self accessAddressBookWithEmergencyContact:YES];
        interactiveResult = YES;
    } else if ([nameString isEqualToString:@"GET_LOCATION"]) {
        //  获取经纬度
        [self accessLocationInfo];
        interactiveResult = YES;
    } else if ([nameString isEqualToString:@"ENVIRONMENT_PARAMS"]) {
        //  获取环境变量参数
        [self gainEnvironmentParam];
        interactiveResult = YES;
    } else if ([nameString isEqualToString:@"RETURN_HOMEPAGE"]) {
        //  返回首页
        if (self.delegate && [self.delegate respondsToSelector:@selector(thorReturnHomePage)]) {
            [self.delegate thorReturnHomePage];
        }
        //  进入页面重新刷新
        self.refreshStatus = YES;
        interactiveResult = YES;
    } else if ([nameString isEqualToString:@"APP_LOGIN"]) {
        //  登陆
        if (self.delegate && [self.delegate respondsToSelector:@selector(thorWebViewUserLogin)]) {
            [self.delegate thorWebViewUserLogin];
        }
        //  进入页面重新刷新
        self.refreshStatus = YES;
        interactiveResult = YES;
    } else if ([nameString isEqualToString:@"PAY_RESULT"]) {
        //  返回第三方APP支付结果
        if (self.delegate && [self.delegate respondsToSelector:@selector(thorPayResultWithVC:andCode:resultParam:)]) {
            NSString *payResultCode = [NSString string];
            if (paramsDictionary[@"payResultCode"]) {
                payResultCode = [paramsDictionary[@"payResultCode"] description];
            }
            NSDictionary *resultParam = [NSDictionary dictionary];
            if (paramsDictionary[@"payResultData"]) {
                resultParam = paramsDictionary[@"payResultData"];
            }
            [self.delegate thorPayResultWithVC:self andCode:payResultCode resultParam:resultParam];
        }
        //  进入页面重新刷新
        self.refreshStatus = YES;
        interactiveResult = YES;
    } else if ([nameString isEqualToString:@"APP_ALIPAY"]) {
        //  跳转到支付宝认证
        NSString *userId = [NSString string];
        NSString *moxieKey = [NSString string];
        if ([paramsDictionary[@"userId"] description] && [paramsDictionary[@"userId"] description].length > 0) {
            userId = [paramsDictionary[@"userId"] description];
        }
        if ([paramsDictionary[@"moxieKey"] description] && [paramsDictionary[@"moxieKey"] description].length > 0) {
            moxieKey = [paramsDictionary[@"moxieKey"] description];
        }
        /***必须配置的基本参数*/
        [MoxieSDK shared].delegate = self;
        [MoxieSDK shared].userId = userId;
        [MoxieSDK shared].apiKey = moxieKey;
        [MoxieSDK shared].backImageName = @"thor_nav_back";
        [MoxieSDK shared].fromController = self;
        //  支付宝
        [MoxieSDK shared].taskType = @"alipay";
        [[MoxieSDK shared] startFunction];
        
        self.refreshStatus = NO;
        interactiveResult = YES;
    } else if ([nameString isEqualToString:@"RISK_RESULT"]) {
        // 返回第三方认证结果
        if (self.delegate && [self.delegate respondsToSelector:@selector(thorRiskResultWithVC:andCode:resultParam:)]) {
            NSString *payResultCode = [NSString string];
            if (paramsDictionary[@"riskResultCode"]) {
                payResultCode = [paramsDictionary[@"riskResultCode"] description];
            }
            NSDictionary *resultParam = [NSDictionary dictionary];
            if (paramsDictionary[@"riskResultData"]) {
                resultParam = paramsDictionary[@"riskResultData"];
            }
            [self.delegate thorPayResultWithVC:self andCode:payResultCode resultParam:resultParam];
        }
        self.refreshStatus = YES;
        interactiveResult = YES;
    } else {
        interactiveResult = NO;
    }
    return interactiveResult;
}

//  魔蝎认证结果
-(void)receiveMoxieSDKResult:(NSDictionary*)resultDictionary{
    //  code = -1, 用户未进行操作
    //  code 1,  用户认证成功
    //  code 2,  认证处理中
    int code = [resultDictionary[@"code"] intValue];
    //  支付宝认证结果
    NSString *alipayResultJs = [NSString string];
    if (code == 1 || code == 2) {
        //  支付宝认证成功
        alipayResultJs = [NSString stringWithFormat:@"nativeAlipayAuthSuccess()"];
    } else {
        //  支付宝认证失败
        alipayResultJs = [NSString stringWithFormat:@"nativeAlipayAuthFail()"];
    }
    [self.webView evaluateJavaScript:alipayResultJs completionHandler:nil];
}

#pragma mark - 获取埋点基础参数
- (void)gainEnvironmentParam{
    [ThorBaseManager baseDeviceParamsCompleted:^(NSString *environmentParams) {
        NSString *environmentParam = environmentParams;
        NSString *environmentParamOcToJs = [NSString stringWithFormat:@"nativeGetEnvironmentParam('%@')", [environmentParam mars_base64EncodedString]];
        //  上传地理位置
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.webView evaluateJavaScript:environmentParamOcToJs completionHandler:nil];
        });
    }];
}

#pragma mark - 地理位置获取
- (void)accessLocationInfo{
    //  获取地理位置信息
    [self.locationManager mars_getCurrentGeolocationsCompled:^(NSArray *placemarks) {
        if (placemarks.count > 0) {
            CLPlacemark *placeMark = placemarks[0];
            CLLocation *location = placeMark.location;
            CLLocationCoordinate2D coordinate = location.coordinate;
            //  经度
            NSString *longitude = [NSString stringWithFormat:@"%.6f",coordinate.longitude];
            //  纬度
            NSString *latitude = [NSString stringWithFormat:@"%.6f",coordinate.latitude];
            
            NSMutableDictionary *paramsDict = [NSMutableDictionary dictionary];
            [paramsDict setValue:longitude forKey:@"coordinateX"];
            [paramsDict setValue:latitude forKey:@"coordinateY"];
            NSString *paramsJsonString = [paramsDict mars_JSONString];
            
            NSString *addressOcToJs = [NSString stringWithFormat:@"nativeGetLocation('%@')", [paramsJsonString mars_base64EncodedString]];
            //  上传地理位置
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.webView evaluateJavaScript:addressOcToJs completionHandler:nil];
            });
        }
    }];
}

#pragma mark - 通讯录上传通讯录
//  访问通讯录
- (void)accessAddressBookWithEmergencyContact:(BOOL)gainEmergencyContact{
    __weak typeof(self) weakSelf = self;
    [self.addressBookManager mars_accessAddressBookResult:^(BOOL access, NSString *addressBookData) {
        if (access) {
            //  允许访问通讯录
            NSString *addressBookDataEncode = [NSString string];
            if (addressBookData && [addressBookData isKindOfClass:[NSString class]]) {
                //  存储通讯录
                self.phoneParamsString = addressBookData;
                addressBookDataEncode = [addressBookData mars_base64EncodedString];
            }
            
            if (gainEmergencyContact) {
                //  访问通讯录联系人获取紧急联系人
                [weakSelf.emergencyContactManager mars_systemAddressBookViewController];
            } else {
                NSString *addressOcToJs = [NSString stringWithFormat:@"nativeAddressBook('%@')", addressBookDataEncode];
                //  上传通讯录信息 (在iOS11 上不在主线程上运行可能会奔溃)
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.webView evaluateJavaScript:addressOcToJs completionHandler:nil];
                });
            }
        } else {
            //  不允许访问通讯录, 弹框跳转到设置通讯录
            [MarsAuthorizeManager mars_authorizeAddressBook];
        }
    }];
}

#pragma mark - EmergencyContactManagerDelegate 获取紧急联系人
/** 选择紧急联系人 */
- (void)emergencyContactSelectPersonName:(NSString *)name personPhone:(NSString *)phone{
    NSMutableDictionary *paramsDict = [NSMutableDictionary dictionary];
    NSMutableDictionary *emergencyContactDict = [NSMutableDictionary dictionary];
    [emergencyContactDict setValue:name forKey:@"name"];
    [emergencyContactDict setValue:phone forKey:@"phone"];
    [paramsDict setValue:emergencyContactDict forKey:@"EmergencyContact"];
    [paramsDict setValue:self.phoneParamsString forKey:@"addressList"];
    NSString *paramsString = [paramsDict mars_JSONString];
    
    //  上传紧急联系人
    NSString *addressOcToJs = [NSString stringWithFormat:@"nativeGetEmergencyContact('%@')", [paramsString mars_base64EncodedString]];
    [self.webView evaluateJavaScript:addressOcToJs completionHandler:nil];
}

- (NSString *)addSDKInfoRequestUrlParamas:(NSURL *)requestUrl{
    //  分割符号
    NSString *separator = ([requestUrl.absoluteString rangeOfString:@"?"].location == NSNotFound) ? @"?" : @"&";
    //  添加sdkInfo
    NSMutableDictionary *sdkInfoDict = [NSMutableDictionary dictionary];
    [sdkInfoDict setValue:@"231" forKey:@"sdkVersion"];
    NSString *sdkInfoJsonString = [[sdkInfoDict mars_JSONString] mars_base64EncodedString];
    //  拼接参数的URL
    NSString *appendAppInfoUrl = [NSString stringWithFormat:@"%@%@sdkInfo=%@",requestUrl.absoluteString, separator, sdkInfoJsonString];
    //  过滤URL
    appendAppInfoUrl = [appendAppInfoUrl stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    appendAppInfoUrl = [appendAppInfoUrl stringByReplacingOccurrencesOfString:@" " withString:@""];
    appendAppInfoUrl = [appendAppInfoUrl stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    
    //  URL safe Encode
    appendAppInfoUrl = [appendAppInfoUrl mars_urlEncode];
    return appendAppInfoUrl;
}

#pragma - setter/getter
- (UIView *)lineView{
    if (_lineView == nil) {
        _lineView = [[UIView alloc] init];
        _lineView.backgroundColor = [UIColor clearColor];
        _lineView.frame = CGRectMake(0.0, Mars_Navigation_Bar_Height, Mars_Screen_Width, 1.0);
    }
    return _lineView;
}

- (WKWebView *)webView{
    if (_webView == nil) {
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0.0, CGRectGetMaxY(_lineView.frame), Mars_Screen_Width, Mars_Screen_Height - CGRectGetMaxY(_lineView.frame) - Mars_TabBar_Addition_Height)];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
    }
    return _webView;
}

/** 进度条 */
- (ThorProgressLayer *)progressLayer{
    if (_progressLayer == nil) {
        _progressLayer = [ThorProgressLayer layerWithFrame:CGRectMake(0.0, 0.0, Mars_Screen_Width, 2.0) progressColor:_progressColor];
    }
    return _progressLayer;
}

/** 通讯录访问 */
- (MarsAddressBookManager *)addressBookManager{
    if (_addressBookManager == nil) {
        _addressBookManager = [[MarsAddressBookManager alloc] init];
    }
    return _addressBookManager;
}

/** 紧急联系人 */
- (MarsEmergencyContactManager *)emergencyContactManager{
    if (_emergencyContactManager == nil) {
        _emergencyContactManager = [[MarsEmergencyContactManager alloc] init];
        _emergencyContactManager.delegate = self;
    }
    return _emergencyContactManager;
}

/** 定位地址 */
- (MarsLocationManager *)locationManager{
    if (_locationManager == nil) {
        _locationManager = [[MarsLocationManager alloc] init];
    }
    return _locationManager;
}

/** 网络请求 */
- (ThorServiceManager *)serviceManager{
    if (!_serviceManager) {
        _serviceManager = [[ThorServiceManager alloc] init];
        _serviceManager.delegate = self;
    }
    return _serviceManager;
}

- (void)dealloc{
    [self.webView removeObserver:self forKeyPath:@"title" context:NULL];
}

- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
